package com.my.lab.util;

import java.util.HashMap;
import java.util.List;

import com.my.lab.MylaberatorRoomActivity;
import com.my.lab.R;
import com.my.lab.activity.BingTuActivity;
import com.my.lab.activity.UdpActivity;
import com.my.lab.activity.WebViewActivity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;

public class WifiUtil {
    private final static String TAG = "WifiAdmin";

    private StringBuffer mStringBuffer = new StringBuffer();
    private HashMap<String, Integer> infoMap = new HashMap<String, Integer>();
    private List<ScanResult> listResult;

    private ScanResult mScanResult;

    // 定义WifiManager对象
    private WifiManager mWifiManager;

    // 定义WifiInfo对象
    private WifiInfo mWifiInfo;

    // 网络连接列表
    private List<WifiConfiguration> mWifiConfiguration;

    // 定义一个WifiLock
    WifiLock mWifiLock;

    Context context;

    /**
     * 构造方法
     */
    public WifiUtil(Context context) {
        this.context = context;
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    public void getInstance(Context context) {
        if (mWifiManager == null)
            mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (mWifiInfo == null)
            mWifiInfo = mWifiManager.getConnectionInfo();
    }

    /**
     * 打开Wifi网卡
     */
    public void openNetCard() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    /**
     * 关闭Wifi网卡
     */
    public void closeNetCard() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 检查当前Wifi网卡状态
     */
    public void checkNetCardState() {
        if (mWifiManager.getWifiState() == 0) {
            Log.i(TAG, "网卡正在关闭");
        } else if (mWifiManager.getWifiState() == 1) {
            Log.i(TAG, "网卡已经关闭");
        } else if (mWifiManager.getWifiState() == 2) {
            Log.i(TAG, "网卡正在打开");
        } else if (mWifiManager.getWifiState() == 3) {
            Log.i(TAG, "网卡已经打开");
        } else {
            Log.i(TAG, "没有获取到状态");
        }
    }

    /**
     * 检测wifi是否可用
     * 
     * @return
     */
    public boolean isWifiEnabled() {
        if (mWifiManager.getWifiState() == 2 || mWifiManager.getWifiState() == 3)
            return true;
        return false;
    }

    /**
     * 扫描周边网络
     */
    public void scan() {
        mWifiManager.startScan();
        listResult = mWifiManager.getScanResults();
        if (listResult != null) {
            Log.i(TAG, "当前区域存在无线网络，请查看扫描结果");
        } else {
            Log.i(TAG, "当前区域没有无线网络");
        }
    }

    /**
     * 得到扫描结果
     */
    public HashMap<String, Integer>getScanResult() {
        // 每次点击扫描之前清空上一次的扫描结果
        if (mStringBuffer != null) {
            mStringBuffer = new StringBuffer();
        }
        // 开始扫描网络
        scan();
        listResult = mWifiManager.getScanResults();
        if (listResult != null) {
            for (int i = 0; i < listResult.size(); i++) {
                mScanResult = listResult.get(i);
                infoMap.put(mScanResult.SSID, calculateSignalLevel(mScanResult.level));
                mStringBuffer = mStringBuffer.append("NO.").append(i + 1).append(" :").append(mScanResult.SSID).append("->信号:").append(calculateSignalLevel(mScanResult.level)).append("->").append(mScanResult.BSSID).append("->").append(mScanResult.capabilities)
                        .append("->").append(mScanResult.frequency).append("->").append(mScanResult.level).append("->").append(mScanResult.describeContents()).append("\n\n");
            }
        }
        Log.i(TAG, mStringBuffer.toString());
        Log.i(TAG, infoMap.toString());
        return infoMap ;
    }

    /**
     * 连接指定网络
     */
    public void connect() {
        mWifiInfo = mWifiManager.getConnectionInfo();

    }

    /**
     * 断开当前连接的网络
     */
    public void disconnectWifi() {
        int netId = getNetworkId();
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
        mWifiInfo = null;
    }

    /**
     * 检查当前网络状态
     * 
     * @return String
     */
    public void checkNetWorkState() {
        if (mWifiInfo != null) {
            Log.i(TAG, "网络正常工作");
        } else {
            Log.i(TAG, "网络已断开");
        }
    }

    public int calculateSignalLevel(int rssi) {
        return WifiManager.calculateSignalLevel(rssi, 6);
    }

    /**
     * 得到连接的ID
     */
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    /**
     * 得到IP地址
     */
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    // 锁定WifiLock
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock
    public void releaseWifiLock() {
        // 判断时候锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的网络
    public List<WifiConfiguration> getConfiguration() {
        return mWifiConfiguration;
    }

    // 指定配置好的网络进行连接
    public void connectConfiguration(int index) {
        // 索引大于配置好的网络索引返回
        if (index >= mWifiConfiguration.size()) {
            return;
        }
        // 连接配置好的指定ID的网络
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId, true);
    }

    // 得到MAC地址
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    // 得到接入点的BSSID
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    /**
     * 得到接入点ssid
     * 
     * @return
     */
    public String getSSID() {
        return (mWifiInfo == null) ? "NULL" : (mWifiInfo.getSSID() == null) ? "NULL" : mWifiInfo.getSSID();
    }

    // 得到WifiInfo的所有信息包
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    // 添加一个网络并连接
    public boolean addNetwork(int type, String ssid, String password) {

        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + ssid + "\"";

        WifiConfiguration tempConfig = this.IsExsits(ssid);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        switch (type) {
        case 1:
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
            break;
        case 2:
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
            break;

        case 3:
            config.preSharedKey = "\"" + password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        int wcgID = mWifiManager.addNetwork(config);
        boolean result = mWifiManager.enableNetwork(wcgID, true);
        Log.d(TAG, "enabled network return : " + result);
        if (result) {
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notification = new Notification(R.drawable.ic_launcher, "连接到无线热点yimi", System.currentTimeMillis());
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            Intent i = new Intent(context, UdpActivity.class);
            PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0);
            notification.setLatestEventInfo(context, "连接上无线热点zhidian", "点击打开应用", pi);
            manager.notify(0, notification);
        }
        return result;
    }

    private WifiConfiguration IsExsits(String ssid) {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + ssid + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }
}